package net.cardgame.oraclecard.common;

import java.io.InputStream;

import jp.jma.oraclecard.MyApplication;
import net.cardgame.orcalecard.utils.FileUtils;
import uk.co.senab.bitmapcache.BitmapLruCache;
import uk.co.senab.bitmapcache.CacheableBitmapDrawable;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class ThreadLoadImage extends Thread {
	String patch;
	BitmapFactory.Options option;
	int what;
	Handler handler;
	private BitmapLruCache mCache;
	Boolean cacheOnMemory;

	public ThreadLoadImage(Handler handler, String patch, ImageView imageview,
			int what, boolean cacheOnMemory) {
		// TODO Auto-generated constructor stubt
		this.cacheOnMemory = cacheOnMemory;
		mCache = MyApplication.getInstance().getBitmapCache();
		this.handler = handler;
		this.what = what;
		this.patch = patch;
		this.option = new Options();
		if (imageview != null) {
			option.outHeight = imageview.getHeight();
			option.outWidth = imageview.getWidth();
		}
	}

	public ThreadLoadImage(Context context, Handler handler, String patch,
			ImageView imageview, int what) {
		// TODO Auto-generated constructor stubt
		this.cacheOnMemory = true;
		mCache = MyApplication.getInstance().getBitmapCache();
		this.handler = handler;
		this.what = what;
		this.patch = patch;
		this.option = new Options();
		if (imageview != null) {
			option.outHeight = imageview.getHeight();
			option.outWidth = imageview.getWidth();
		}
		imageview = null;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		BitmapDrawable wrapper = mCache.getFromMemoryCache(patch);
		if (wrapper != null && !wrapper.getBitmap().isRecycled()) {
			Message msg = handler.obtainMessage(what);
			msg.obj = wrapper;
			wrapper = null;
			msg.what = what;
			handler.sendMessage(msg);
			return;
		}
		CacheableBitmapDrawable result = mCache.getFromDiskCache(patch, option);
		if (null == result || result.getBitmap().isRecycled()) {
			try {
				InputStream is = FileUtils.decrytToInputStream(patch);
				// Add to mCache
				result = mCache.put(patch, is, option, cacheOnMemory);
			} catch (Exception e) {
			}
		}
		Message msg = handler.obtainMessage(what);
		msg.obj = result;
		result = null;
		msg.what = what;
		handler.sendMessage(msg);
	}
}
